<?php
/**
 * 运费管理
 **/
class openapi_api_function_v1_dly extends openapi_api_function_abstract implements openapi_api_function_interface{

	/**
	 * 获取运费模板
	 * @param
	 * @return
	 * @author hmg
	 **/
	public function getdlytype($params,&$code,&$sub_msg)
	{
		$member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $store = app::get('business')->model('storemanger')->getList("store_id,store_grade",array('account_id'=>$member_id));
        $store_id = $store[0]['store_id'];

		$mdl_dlytype = app::get('b2c')->model('dlytype');
        $dlytype = $mdl_dlytype->getList('dt_id,dt_name', array('store_id'=>$store_id, 'dt_status'=>'1'));

        $current_dlytype = app::get('business')->model('goods')->get_dlytype($params['goods_id'], $store_id);
        if(!empty($current_dlytype)){
            foreach($dlytype as $k=>$v){
                if($v['dt_id'] == $current_dlytype[0]['dt_id']){
                    $dlytype[$k]['default'] = 1;
                    break;
                }
            }
        }

        return $this->apiData(true,$dlytype,200);
	}

    /**
     * 设置商品运费模板
     * @param
     * @return
     * @author hmg
     **/
    public function setgoodsdlytype($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $store = app::get('business')->model('storemanger')->getList("store_id,store_grade",array('account_id'=>$member_id));
        $store_id = $store[0]['store_id'];
        $data = $params;
        $data['dly_id'] = $params['dt_id'];
        unset($data['dt_id']);
        $data['manual'] = 'normal';

        $dlytype = app::get('b2c')->model('dlytype')->getList('dt_id', array('store_id'=>$store_id));
        foreach($dlytype as $v){
            $dly_id[] = $v['dt_id'];
        }

        $db = kernel::database();
        $transaction= $db->beginTransaction();
        if($dly_id){
            $sql0 = 'delete from sdb_b2c_goods_dly where goods_id='.$data['goods_id'].' and dly_id in('.implode(',', $dly_id).") and manual='normal'";
            if(!$db->exec($sql0)){
                $db->rollback();
            }
        }

        if(app::get('b2c')->model('goods_dly')->save($data)){
            $db->commit($transaction);
            return $this->apiData(true, null, 200, app::get('business')->_('设置成功'));
        }else{
            $db->rollback();
            return $this->apiData(false, null, 400, app::get('business')->_('设置失败'));
        }
    }

}